import {stateFormat} from './state.js'

const reg_onClick = /onClick\=\'(.*?)\'/g
const reg_method = /(.*?)\(/
const reg_FnParam =  /\((.*?)\)/

const eventPool = []

function eventFormat(template){      
    template = template.replace(reg_onClick, function(node,key){
     
        const _flag = randNum()        
        eventPool.push({
            flag:_flag,
            handle: key.trim(),
            type: 'click'

        })
       return `data-dom=${_flag}`
    })     
    return template
}


function bindEvent (methods,state){
    
    const oItems = document.getElementsByTagName('*')  

    eventPool.forEach(event=>{          
       
       
        for (let i = 0; i< oItems.length; i++){
            let oItem = oItems[i]                    
            if (parseInt(oItem.dataset.dom) === event.flag){             
              
               
               // console.log(222,method(param))
                function goFn(){
                    let method = event['handle'].match(reg_method)[1] 
                    let param = event['handle'].match(reg_FnParam) [1]      

                    param = checkParam(param)
                    if (parseInt(param)!==NaN){param =parseInt(param)}
                    
                    method =  methods[method]                  
                    method(param)
                }
                oItem.addEventListener(event.type,goFn,false)

            }      
           
        }             
      
    })
}

const reg_check_str = /^[\'|\"](.*?)[\'|\"]/
const reg_str = /[\'|\"]/g
function checkParam(param){
    
    if (reg_check_str.test(param)){
      
        return param.replace(reg_str,'')
    }  

    switch (param) {
        case 'true':
            return true
        case 'false':
            return false
        default: 
        return param
    }
}
function randNum(){
    return Date.now() + parseInt(Math.random()*10000)
}

export {
    eventFormat,
    bindEvent
}